package bpm.dao.impl.process;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.springframework.jdbc.core.RowMapper;

import bpm.domain.document.Document;
import bpm.domain.process.Node;
import bpm.domain.process.ProcessDefinition;
import bpm.domain.process.WorkItem;
import bpm.domain.process.WorkItemState;
import bpm.domain.user.OrgUser;

/**
 * 
 * @author <a mailto="hwangsyin@gmail.com">King</a>
 *
 */
public class EngineWorkItemMapper implements RowMapper {

	public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
		WorkItem task = new WorkItem();
		
		task.setId(rs.getInt("id"));
		task.setCaseId(rs.getInt("caseid"));
		task.setBatch(rs.getInt("batch"));
		task.setCount(rs.getInt("itemnum"));
		task.setName(rs.getString("name"));
		task.setCaseName(rs.getString("casename"));
		
		String documentId = rs.getString("casedata1");
		if(documentId != null) {
			Document doc = new Document();
			doc.setId(documentId);
			
			task.setDocument(doc);
		}
		
		String nodeId = rs.getString("activityid");
		if(nodeId != null) {
			Node node = new Node();
			node.setId(nodeId);
			node.setName(rs.getString("activityname"));
			
			String pdid = rs.getString("processid");
			if(pdid != null) {
				ProcessDefinition pd = new ProcessDefinition();
				pd.setId(pdid);
				pd.setName(rs.getString("processname"));
				
				node.setProcessDefinition(pd);
			}
			
			task.setNode(node);
		}
		
		String performerId = rs.getString("performer");
		if(performerId != null) {
			OrgUser performer = new OrgUser();
			performer.setId(performerId);
			
			task.setPerformer(performer);
		}
		
		String finisherId = rs.getString("finisher");
		if(finisherId != null) {
			OrgUser finisher = new OrgUser();
			finisher.setId(finisherId);
			
			task.setFinisher(finisher);
		}
		
		//owner
		//oldstate
		int state = rs.getInt("state");
		if(state > 0) {
			task.setState(WorkItemState.idOf(state));
		}
		
		task.setCreateDate(new Date(rs.getLong("createdate")));
		task.setUpdateDate(new Date(rs.getLong("updatedate")));
		
		return task;
	}

}
